﻿
using AiMoBridge.Interface.Client;
using AiMoWindows.Entrance;
using AiMoWindows.Localization;
using AiMoWindows.Server;
using AiMoWindows.Windows.AiAssistant.ViewModels;
using System.Windows;

namespace AiMoWindows.MainActions.AiActions
{
    class AiAskActions(AiAssistantViewModel owner) : IAIReply
    {
        readonly AiAssistantViewModel owner = owner;
        enum QuestionTag
        {
            Empty,
            NewQuestion,
            TooShort,
        }
        public void AiAssistantUI_OnLanguageChanged(object? sender, EventArgs e)
        {
            if (owner.ReplyText.StartsWith("[INIT]"))
            {
                InitReplyText();
            }
        }
        public void InitReplyText()
        {
            string text;
            if (Local.RunningInChinese)
            {
                text = "[INIT]\r\n\r\n你好，我是AiMo，一个AI建模助手。\r\n\r\n请问我任何和Rhino建模有关的问题。" +
                    "\r\n我将会尽力帮助你解决建模问题。我会提供详尽的建模思路，并附上相应的代码。";
            }
            else
            {
                text = "[INIT]\r\n\r\nHI,I'm AiMo. An AI modeling assistant. \r\n\r\n" +
                "Please ask me any question related to AiMoRhino modeling. \r\n" +
                "I'll try my best to help you solve your modeling question. I will generate a detailed modeling process and attach a c# code if possible.";
            }
            owner.ReplyText = text;
        }

        bool inAsk = false;
        public void AskAiButton_Click()
        {
            if (inAsk) return;
            string text = owner.UserInputText.Trim();
            switch (DispathQuestion(text))
            {
                case QuestionTag.Empty:
                    {
                        owner.ShowMessage(Local.Get("Cannot send empty Message"));
                        break;
                    }
                case QuestionTag.TooShort:
                    {
                        owner.ShowMessage(Local.Get("Cannot send too short message"));
                        break;
                    }
                default:
                case QuestionTag.NewQuestion:
                    {
                        ClearAiReply();
                        IAiAskClient askAiClient = GetClient.GetAiAskClient();
                        askAiClient.UpdateEvent += Update;
                        AskAIAsync(askAiClient);
                        break;
                    }
            }
        }

        void Update(ClientEventArgs args)
        {
            AiMoProgram.Instance.UpdateAllWindowState();
        }
        QuestionTag DispathQuestion(string question)
        {
            if (string.IsNullOrWhiteSpace(question))
            {
                return QuestionTag.Empty;
            }
            if (question.Length < 8)
            {
                return QuestionTag.TooShort;
            }
            return QuestionTag.NewQuestion;
        }

        async Task AskAIAsync(IAiAskClient client)
        {
            bool re = false;
            string messageBoxError = "";
            inAsk = true;
            owner.AiAssistantUI.AskCancelButtonEnable = true;
            owner.AiAssistantUI.ChangeAskAiButtonMode(AskAiButtonMode.Connecting);
            await Task.Run(() => { re = client.Ask(out messageBoxError); });
            if (!string.IsNullOrEmpty(messageBoxError)) owner.ShowMessage(messageBoxError);

            Application.Current.Dispatcher.Invoke(StopAnswer);
            inAsk = false;
        }
        public bool IsStreamCancel { get; private set; } = false;
        public void ClearAiReply()
        {
            owner.ReplyText = "";
        }
        void StopAnswer()
        {
            if (IsStreamCancel)
            {
                owner.ShowMessage(Local.Get("Reply cancelled"));
            }
            IsStreamCancel = false;
            owner.AiAssistantUI.ChangeAskAiButtonMode(AskAiButtonMode.CanAsk);
            owner.AiAssistantUI.AskCancelButtonEnable = false;
        }
        public void AskCancelButton_Click()
        {
            IsStreamCancel = true;
        }
        void IAIReply.OnWait(double seconds)
        {
            owner.AiAssistantUI.ChangeAskAiButtonMode(AskAiButtonMode.Waiting);
        }
        void IAIReply.StopWait()
        {
            owner.AiAssistantUI.ChangeAskAiButtonMode(AskAiButtonMode.Replying);
        }
        void IAIReply.AppendReplyWord(string word)
        {
            owner.ReplyText += word;
        }
        IScriptMessage? currentReplyMessage;
        void IAIReply.SetCodeReplyMessage(IScriptMessage message)
        {
            currentReplyMessage = message;
            Application.Current.Dispatcher.Invoke(OpenScriptFormFromReplyCode);
        }
        void IAIReply.BeforeAiReply(string beforeAiReplyText)
        {
            owner.ReplyText += beforeAiReplyText;
        }
        public void OpenScriptFormFromReplyCode()
        {
            if (currentReplyMessage != null)
            {
                AiMoProgram.Instance.OpenNewAimoScriptForm(currentReplyMessage, out string error);
                if (!string.IsNullOrEmpty(error)) owner.ReplyText += error;
            }
        }
    }
}
